package com.letv.whatslive.mongo.dao;


import com.google.common.collect.Lists;
import com.letv.whatslive.common.utils.ObjectUtils;
import com.letv.whatslive.model.PaikeAnchor;
import com.letv.whatslive.model.convert.PaikeAnchorConvert;
import com.letv.whatslive.model.utils.ObjUtils;
import com.letv.whatslive.mongo.BaseDAO;
import com.letv.whatslive.redis.JedisDAO;
import com.mongodb.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * 用户collection操作DAO
 * Created by shenyue on 16-6-14.
 */
@Repository
public class PaikeAnchorDAO extends BaseDAO {

    private final static Logger logger = LoggerFactory.getLogger(PaikeAnchorDAO.class);

    protected String collectionName = "paikeAnchor";

    @Autowired
    protected JedisDAO jedisDAO;
    @Autowired
    protected BankDAO bankDAO;
    @Override
    protected void init() {
        super.init(this.collectionName);
    }

    @Override
    protected long getAutoIncrementId() {
        return idGenerate.generateId(this.collectionName);
    }

    public int saveOrUpdatePaikeAnchor(PaikeAnchor paikeAnchor) {
        WriteResult result = null;
        if(paikeAnchor!=null && paikeAnchor.getId()!=null){
            DBObject query = new BasicDBObject("_id", paikeAnchor.getId());
            DBObject dbo = this.dbCollection.findOne(query);
            if (dbo == null) {//insert
                dbo = PaikeAnchorConvert.castPaikeAnchorToDBObject(paikeAnchor);
                if (dbo != null) {
                    result = this.dbCollection.save(dbo);
                }
            } else {//update
                DBObject update = new BasicDBObject();

                if (paikeAnchor.getSex() >= -1) {
                    update.put("sex", paikeAnchor.getSex());
                }
                if (StringUtils.isNotBlank(paikeAnchor.getAnchorName())) {
                    update.put("anchorName", paikeAnchor.getAnchorName());
                }

                if(StringUtils.isNotBlank(paikeAnchor.getQqId())){
                    update.put("qqId",paikeAnchor.getQqId());
                }
                if(StringUtils.isNotBlank(paikeAnchor.getWeixinId())){
                    update.put("weixinId",paikeAnchor.getWeixinId());
                }
                if(StringUtils.isNotBlank(paikeAnchor.getAlipayId())){
                    update.put("alipayId",paikeAnchor.getAlipayId());
                }
                if(StringUtils.isNotBlank(paikeAnchor.getProvince())){
                    update.put("province",paikeAnchor.getProvince());
                }
                if(StringUtils.isNotBlank(paikeAnchor.getCity())){
                    update.put("city",paikeAnchor.getCity());
                }
                if(StringUtils.isNotBlank(paikeAnchor.getDistrict())){
                    update.put("district",paikeAnchor.getDistrict());
                }
                if(StringUtils.isNotBlank(paikeAnchor.getBankCardNo())){
                    update.put("bankCardNo",paikeAnchor.getBankCardNo());
                }
                if(StringUtils.isNotBlank(paikeAnchor.getIdCardPicture())){
                    update.put("idCardPicture",paikeAnchor.getIdCardPicture());
                }
                if(paikeAnchor.getBankId()!=null){
                    update.put("bankId",paikeAnchor.getBankId());
                }
                update.put("updateTime", System.currentTimeMillis());
               result = this.dbCollection.update(query, new BasicDBObject("$set", update), true, false);
            }
        }else{
            return ObjectUtils.toInteger(this.insert(PaikeAnchorConvert.castPaikeAnchorToDBObject(paikeAnchor)));
        }
        return result.getN();

    }

    /**
     * 查询用户列表
     *
     * @param params 模糊查询的查询条件
     * @param orders 排序的条件
     * @param start  查询条件的开始分页数
     * @param limit  查询条件的分页每页条数
     * @return
     */
    public List<PaikeAnchor> getPaikeAnchorListByParams(Map<String, Object> params, Map<String, Object> orders, Integer start, Integer limit) {

        List<PaikeAnchor> result = Lists.newArrayList();
        if (limit == null) {
            limit = DEFAULT_NUM;
        }
        //TODO 临时用于检查错误用户数据
        PaikeAnchor errorPaikeAnchor = new PaikeAnchor();
        try {
            //dbObj 类似于 mysql 查询中的 where 关键字，可以添加各种搜索条件
            BasicDBObject order = getOrderParams(orders);
            BasicDBObject query = getBasicDBObjectByParams(params);
            Integer skip = start == null ? 0 : start;
            DBCursor cur = this.dbCollection.find(query).skip(skip).sort(order).limit(limit);//按createTime的值倒叙排列
            while (cur.hasNext()) {
                DBObject dbObject = cur.next();
                PaikeAnchor paikeAnchor = PaikeAnchorConvert.castDBObjectToPaikeAnchor(dbObject);
                errorPaikeAnchor = paikeAnchor;
                setValueToPaikeAnchor(paikeAnchor);
                result.add(paikeAnchor);
            }
        } catch (Exception e) {
            logger.error("paikeId:<"+errorPaikeAnchor.getId()+"> error:<"+e.getMessage()+">",e);
        }
        return result;
    }

    /**
     * 查询用户列表(api)
     *
     * @param params 模糊查询的查询条件
     * @param orders 排序的条件
     * @param start  查询条件的开始分页数
     * @param limit  查询条件的分页每页条数
     * @return
     */
    public List<PaikeAnchor> getPaikeAnchorListByParamsApi(Map<String, Object> params, Map<String, Object> orders, Integer start, Integer limit) {

        List<PaikeAnchor> result = Lists.newArrayList();
        if (limit == null) {
            limit = DEFAULT_NUM;
        }
        try {
            //dbObj 类似于 mysql 查询中的 where 关键字，可以添加各种搜索条件
            BasicDBObject order = getOrderParams(orders);
            BasicDBObject query = getBasicDBObjectByParams(params);
            DBCursor cur = this.dbCollection.find(query).skip((start - 1) * limit).sort(order).limit(limit);//按createTime的值倒叙排列
            while (cur.hasNext()) {
                DBObject dbObject = cur.next();
                PaikeAnchor paikeAnchor = PaikeAnchorConvert.castDBObjectToPaikeAnchor(dbObject);
                setValueToPaikeAnchor(paikeAnchor);
                result.add(paikeAnchor);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    public List<PaikeAnchor> getAllPaikeAnchorByParams(Map<String, Object> params){
        List<PaikeAnchor> result = Lists.newArrayList();
        try {
            //dbObj 类似于 mysql 查询中的 where 关键字，可以添加各种搜索条件
            BasicDBObject query = getBasicDBObjectByParams(params);
            DBCursor cur = this.dbCollection.find(query);
            while (cur.hasNext()) {
                DBObject dbObject = cur.next();
                PaikeAnchor paikeAnchor = PaikeAnchorConvert.castDBObjectToPaikeAnchor(dbObject);
                setValueToPaikeAnchor(paikeAnchor);
                result.add(paikeAnchor);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     * 根据主键查询一个用户
     * @param uid 用户主键
     * @return 一个PaikeAnchor对象
     */
    public PaikeAnchor getPaikeAnchorById(Long uid) {
        BasicDBObject query = new BasicDBObject();
        PaikeAnchor paikeAnchor = new PaikeAnchor();
        query.put("_id", uid);
        DBObject dbObject = this.dbCollection.findOne(query);
        if (dbObject == null) return null;
        try {
            paikeAnchor = PaikeAnchorConvert.castDBObjectToPaikeAnchor(dbObject);
            setValueToPaikeAnchor(paikeAnchor);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return paikeAnchor;
    }


    /**
     * 根据用户ID的集合查询一组用户
     * @param idList
     * @return
     */
    public Map<Long ,PaikeAnchor> getPaikeAnchorsByIds(List<Long> idList){
        Map<Long ,PaikeAnchor> paikeAnchors = new HashMap<Long, PaikeAnchor>();
        BasicDBList values = new BasicDBList();
        for (Long id : idList) {
            values.add(id);
        }
        BasicDBObject queryCondition = new BasicDBObject();
        queryCondition.put("_id", new BasicDBObject("$in", values));
        DBCursor cur = this.dbCollection.find(queryCondition);
        while (cur.hasNext()) {
            DBObject dbObject = cur.next();
            PaikeAnchor paikeAnchor = PaikeAnchorConvert.castDBObjectToPaikeAnchor(dbObject);
            setValueToPaikeAnchor(paikeAnchor);
            paikeAnchors.put(paikeAnchor.getId(), paikeAnchor);
        }
        return paikeAnchors;
    }

    /**
     * 查询用户的数量
     * @param params 查询条件参数
     * @return 满足条件的文档记录数
     */
    public Long countPaikeAnchorByParams(Map params) {
        //dbObj 类似于 mysql 查询中的 where 关键字，可以添加各种搜索条件
        BasicDBObject query = getBasicDBObjectByParams(params);
        return this.dbCollection.count(query);
    }

    /**
     * 保存用户信息
     * @param paikeAnchor
     * @return
     */
    public PaikeAnchor savePaikeAnchor(PaikeAnchor paikeAnchor) {
        try {
            paikeAnchor.setId(getAutoIncrementId());
            DBObject dbo = PaikeAnchorConvert.castPaikeAnchorToDBObject(paikeAnchor);
            WriteResult wr = this.dbCollection.insert(dbo);
            return paikeAnchor;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return null;
        }
    }

    /**
     * 更新用户基本信息
     * @param paikeAnchor
     */
    public void updatePaikeAnchor(PaikeAnchor paikeAnchor) {
        DBObject queryCondition = new BasicDBObject();
        Long paikeAnchorId = paikeAnchor.getId();
        queryCondition.put("_id", paikeAnchorId); // 用来确定要修改的文档
        DBObject setValue = PaikeAnchorConvert.castPaikeAnchorToDBObject(paikeAnchor);
        //剔除主键修改
        if (setValue.containsKey("_id")) {
            setValue.removeField("_id");
        }
        DBObject values = new BasicDBObject("$set", setValue);
        this.dbCollection.update(queryCondition, values, false, false);
    }

    /**
     * 根据用户ID删除用户
     * @param uid
     */
    public void deletePaikeAnchor(Long uid){
        BasicDBObject query = new BasicDBObject();
        query.put("_id", uid);
        this.dbCollection.remove(query);
    }

    /**
     * 获取排序的BasicDBObject对象
     * @param orders
     * @return
     */
    private BasicDBObject getOrderParams(Map<String, Object> orders) {
        BasicDBObject order = new BasicDBObject();
        if(null != orders &&orders.size()>0){
            for(String key : orders.keySet()){
                order.append(key, Integer.valueOf(String.valueOf(orders.get(key))));
            }
        }else{
            //默认按照创建时间排序
            order.append("createTime", -1);
        }
        return order;
    }

    /**
     * 根据查询参数Map获取查询条件对象
     * @param params 查询参数Map
     * @return
     */
    private BasicDBObject getBasicDBObjectByParams(Map params){
        //dbObj 类似于 mysql 查询中的 where 关键字，可以添加各种搜索条件
        BasicDBObject query = new BasicDBObject();// 新建查询基类对象 dbo
        if (params != null && params.size() > 0) {
            if(params.get("userId")!=null){
                query.put("userId",ObjectUtils.toLong(params.get("userId")));
            }
            if(params.get("idCardNo")!=null){
                query.put("idCardNo",ObjectUtils.toString(params.get("idCardNo")));
            }
            if (params.get("anchorName") != null) {
                Pattern pattern = Pattern.compile("^.*" + params.get("anchorName") + ".*$", Pattern.CASE_INSENSITIVE);
                query.put("anchorName", pattern);
            }
            if (params.get("anchorName_exactly") != null) {
                query.put("anchorName", ObjectUtils.toString(params.get("anchorName_exactly")));
            }
            if (params.get("paikeAnchorIdNotEqual") != null) {
                query.put("_id", new BasicDBObject("$ne", ObjectUtils.toLong(params.get("paikeAnchorIdNotEqual"))));
            }
            if(params.get("startTime_start") != null && params.get("startTime_end") != null){
                query.put("createTime", new BasicDBObject("$gt",
                        ObjectUtils.toLong(params.get("startTime_start"))).append("$lte", ObjectUtils.toLong(params.get("startTime_end"))));

            }
            if(params.get("paikeSociatyId")!=null){
                query.put("paikeSociatyId",ObjectUtils.toLong(params.get("paikeSociatyId")));
            }
            if(params.get("paikeSociatyId_Not")!=null){
                query.put("paikeSociatyId", new BasicDBObject("$ne", ObjectUtils.toLong(params.get("paikeSociatyId_Not"))));
            }

            if (params.get("nameOrId") != null) {
                BasicDBList values = new BasicDBList();
                Pattern pattern = Pattern.compile("^.*" + params.get("nameOrId") + ".*$", Pattern.CASE_INSENSITIVE);
                values.add(new BasicDBObject("_id", ObjectUtils.toLong(params.get("nameOrId"))));
                values.add(new BasicDBObject("anchorName", pattern));
                query.put("$or", values);
            }
            if(params.get("hasPaikeSociaty")!=null){
                query.put("paikeSociatyId", new BasicDBObject("$exists", ObjectUtils.toBoolean(params.get("hasPaikeSociaty"))));
            }
			
		}
        return query;
    }

    /**
     * 设置用户信息中的特殊值
     * @param paikeAnchor
     */
    private void setValueToPaikeAnchor(PaikeAnchor paikeAnchor) {
//        paikeAnchor.setCreateTimeStr(paikeAnchor.getCreateTime() != null ?
//                DateUtils.long2YMDHMS(paikeAnchor.getCreateTime()) : "");
        paikeAnchor.setAddressStr((paikeAnchor.getProvince()!=null?paikeAnchor.getProvince():"") + (paikeAnchor.getCity()!=null?paikeAnchor.getCity():"") + (paikeAnchor.getDistrict()!=null?paikeAnchor.getDistrict():""));
        paikeAnchor.setBankStr((paikeAnchor.getBankId() != null ? bankDAO.getBankById(paikeAnchor.getBankId()).getBankName() : "") + (paikeAnchor.getBankCardNo() != null ? paikeAnchor.getBankCardNo():""));

    }

    /**
     * 根据用户ID列表获取用户列表
     * @param ids
     * @return
     */
    public List<PaikeAnchor> getPaikeAnchorListByIds(String ids) {

        List<PaikeAnchor> result = Lists.newArrayList();

        try {

            BasicDBList values = new BasicDBList();
            String[] idList = ids.split(",");
            for (String id : idList) {
                values.add(ObjectUtils.toLong(id));
            }

            BasicDBObject queryCondition = new BasicDBObject();
            queryCondition.put("_id", new BasicDBObject("$in", values));
            DBCursor cur = this.dbCollection.find(queryCondition);
            while (cur.hasNext()) {

                DBObject dbObject = cur.next();
                PaikeAnchor paikeAnchor = PaikeAnchorConvert.castDBObjectToPaikeAnchor(dbObject);
                result.add(paikeAnchor);
            }
        } catch (Exception e) {

            logger.error("getPaikeAnchorListByIds error ids===" + ids, e);
        }
        return result;
    }

    /**
     * 根据查询条件获取用户ID列表
     * @param params 查询条件
     * @param orders 排序条件
     * @return
     */
    public List<Long> getPaikeAnchorIdsByParams(Map<String, Object> params, Map<String, Object> orders) {

        List<Long> result = Lists.newArrayList();

        try {

            BasicDBObject query = getBasicDBObjectByParams(params);
            BasicDBObject order = getOrderParams(orders);
            DBCursor cur = this.dbCollection.find(query).sort(order);
            while (cur.hasNext()) {
                DBObject dbObject = cur.next();
                result.add(ObjUtils.toLong(dbObject.get("_id")));
            }
        } catch (Exception e) {

            logger.error("getPaikeAnchorIdsByParams error", e);
        }

        return result;
    }

    /**
     * 用户相关信息自增或自减
     * @param paikeAnchorId 用户ID
     * @param columnName 列名
     * @param interval 增减幅度
     * @return 增减后的值
     */
    public Long modifyPaikeAnchorInfoByInterval(Long paikeAnchorId, String columnName, Long interval) {

        // 增减后的值
        Long value = 0L;
        DBObject dbObj = this.dbCollection.findAndModify(new BasicDBObject("_id", paikeAnchorId), new BasicDBObject("$inc",
                new BasicDBObject(columnName, interval)));

        if (dbObj != null) {

            value = ObjectUtils.toLong(dbObj.get(columnName));
        }

        return value;
    }
}

